package com.ys.controller.api.sys;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ys.entity.sys.TbStaticConfig;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ys.dto.DtreeSqlDto;
import com.ys.dto.YsTreeDto;
import com.ys.entity.sys.TsUserInfo;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.TsUserInfoService;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

@Controller
@RequestMapping("/api/inter/tsUserInfo")
public class ApiInterTsUserInfoController {
	
//	private static final Logger logger = Logger.getLogger(ApiAdminLoginController.class);
	
	@Autowired
	private CommonApiService<TsUserInfo> commonApiService;
	@Autowired
	private TsUserInfoService tsUserInfoService;

//	@RequiresPermissions("tsUserInfo:view")
	@RequestMapping("/search")
    @ResponseBody
	public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute TsUserInfo cond,
			Long nodeId
			){

		cond.addField("(A.UserId + '/' + A.UserName) AS nameLinked");
		cond.addField("BA1.HigherLevelPath + ',' + BA1.Name AS nativePlaceName");//籍贯
		cond.addField("BA2.HigherLevelPath + ',' + BA2.Name AS workCityName");//工作地址
		cond.addField("U.OfficeId AS officeId");//所属办公室Id
		cond.addField("B.VReMark AS officeName");//所属办公室地址
		cond.addField("U.RoleIdAttribute AS roleIdAttribute");//用户类型/岗位属性(0职能、1运营)
		
		cond.addLeftJoin("THR_UserArchives U ON U.UserId = A.UserId")
			.addField("U.UserSex AS userSex")//性别
			.addField("U.UserState AS userState")//状态
			.addField("U.RoleIdAttribute AS roleIdAttribute");//岗位属性(0职能、1运营)
		
		cond.addLeftJoin("TB_BaseInfoArea BA1 ON BA1.Code = U.NativePlace AND 1=1");
		cond.addLeftJoin("TB_BaseInfoArea BA2 ON BA2.Code = U.WorkCity AND 1=1");
		cond.addLeftJoin("TB_BaseInfo B ON B.Id = U.OfficeId AND 1=1");
		cond.addLeftJoin("TB_CompanyInfo D ON D.Vid = A.CompanyVid")
			.addField("D.Vname companyVname");
		
		cond.addLeftJoin("TS_OrganizationInfo E ON E.Id = A.Orgid")
		.addField("E.DeptName deptName")
		.addField("E.DeptPath deptPath")
		.addField("E.DeptPathName deptPathName");
		
		cond.addLeftJoin("TS_OrganizationInfo E1 ON E1.Id = E.Pid");
		cond.addLeftJoin("TS_UserInfo E2 on E2.UserId = E1.HeadUserId");
		
		cond.addLeftJoin("TS_UserInfo F on F.UserId = E.HeadUserId")
			.addField("(CASE WHEN A.UserId = E.HeadUserId THEN E2.UserId ELSE F.UserId END) userIdUp") // 若用户是机构负责人，则用户上级为机构上级的部门负责人
			.addField("(CASE WHEN A.UserId = E.HeadUserId THEN E2.UserName ELSE F.UserName END) userNameUp");


		cond.setOrgId(nodeId);
//		if (nodeId != null) {
//			TsOrganizationInfo tsOrganizationInfo = new TsOrganizationInfo().setId(nodeId).queryFirst();
//			cond.addLeftJoin("TS_OrganizationInfo AA on AA.Guid = A.Organizationid")
//				.where("AA.NodeLft >= " + tsOrganizationInfo.getNodeLft())
//				.where("AA.NodeRgt <= " + tsOrganizationInfo.getNodeRgt());
//		}
		
		cond.setOrderby("A.UserId asc");
		
		
		return commonApiService.searchLay(cond);
	}

//	@RequiresPermissions("tsUserInfo:view")
	@RequestMapping("/searchForModal")
    @ResponseBody
	public LayuiTableVoJA searchForModal(@ModelAttribute TsUserInfo cond){
		
		cond.addField("(A.UserId + '/' + A.UserName) AS nameLinked");

		cond.addField("C.UserName userLeaderName");//上级姓名
		cond.addField("O.DeptName AS deptName");
		cond.addField("R.Name AS roleName");
		cond.addField("PO.DeptName AS deptNameP");
		cond.addField("PR.Name AS roleNameP");
		cond.addLeftJoin("TS_OrganizationInfo O ON O.Orgid = A.DeptId AND 1=1");
		cond.addLeftJoin("YS_Role R ON R.Id = A.RoleId AND 1=1");
		cond.addLeftJoin("TS_UserInfo C on C.UserId = A.UserLeader");
		cond.addLeftJoin("TS_OrganizationInfo PO ON PO.Orgid = C.DeptId AND 1=1");
		cond.addLeftJoin("YS_Role PR ON PR.Id = C.RoleId AND 1=1");
		cond.setOrderby("A.UserId asc");
		return commonApiService.searchLay(cond);
	}




	
	@RequestMapping("/dtree")
    @ResponseBody
	public DtreeSqlDto dtree(){
		return tsUserInfoService.dtree();
	}
	
	@RequestMapping("/ysTree")
    @ResponseBody
	public YsTreeDto ysTree(){
		return tsUserInfoService.ysTree();
	}
	
	/**
	 * 新增
	 */
	@PostMapping("/add")
    @ResponseBody
	public R add(HttpServletRequest request, @RequestParam Map<String, Object> params){
		params.put("sourceType",1);
		return tsUserInfoService.add(params);
	}
	
	/**
	 * 编辑
	 */
	@PostMapping("/edit")
    @ResponseBody
	public R edit(HttpServletRequest request, @RequestParam Map<String, Object> params){
		return tsUserInfoService.edit(params);
	}
	
	/**
	 * 重置密码
	 */
	@PostMapping("/resetPass")
    @ResponseBody
	public R resetPass(HttpServletRequest request, @RequestParam Map<String, Object> params){
		
		return tsUserInfoService.resetPass(params);
	}
	
	/**
	 * 批量变更组织机构
	 */
	@RequiresPermissions("tsUserInfo:batchChangeOrg")
	@PostMapping("/batchChangeOrg")
    @ResponseBody
	public R batchChangeOrg(HttpServletRequest request,
			Long orgId,
			String subData) throws Exception{
		
		return tsUserInfoService.batchChangeOrg(orgId, subData);
	}


	/**
	 * 弹出框->员工职级管理
	 */
	@RequestMapping("/searchForModalByUserJobLevelManage")
	@ResponseBody
	public LayuiTableVoJA searchForModalByUserJobLevelManage(@ModelAttribute TsUserInfo cond){

		cond.addField("(A.UserId + '/' + A.UserName) AS nameLinked");
		cond.addLeftJoin("THR_UserArchives UA ON UA.UserId = A.UserId")
				.addField("UA.UserState AS userState")
				.addField("UA.DingDingId AS dingDingId")//员工钉钉id
				.addField("UA.Telephone AS telephone")
				.addField("CASE " +
						"WHEN UA.UserState = 0 THEN '实习' " +
						"WHEN UA.UserState = 1 THEN '试用' " +
						"WHEN UA.UserState = 2 THEN '正式' " +
						"WHEN UA.UserState = 3 THEN '离职' " +
						" ELSE '' END userStateTxt");//员工状态（0实习、1试用、2正式、3离职）
		//过滤在员工职级管理中未新增的员工
		cond.where("( SELECT COUNT ( 1 ) AS num FROM TB_UserJobLevelManage B WHERE B.UserId = A.UserId ) = 0 ");
		cond.where("UA.RoleIdAttribute = 0");//只查询职能岗位属性
		cond.setOrderby("A.UserId asc");
		return commonApiService.searchLay(cond);
	}

	/**
	 * 弹出框->员工银行账户管理
	 */
	@RequestMapping("/searchForModalByUserBank")
	@ResponseBody
	public LayuiTableVoJA searchForModalByUserBank(@ModelAttribute TsUserInfo cond,String conditions){
		//查询条件
		String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_nameLinked");//工号/姓名
		if (nameLinked != null){
			cond.where("A.UserId LIKE '%" + nameLinked + "%'" + " OR  A.UserName LIKE '%" + nameLinked + "%'");
		}
		cond.setStatus(1);
		cond.addField("(A.UserId + '/' + A.UserName) AS _ys_nameLinked");
		cond.setOrderby("A.UserId asc");
		return commonApiService.searchLay(cond);
	}




	//弹出框->仓储部员工列表（FBA装箱单使用）
	@RequestMapping("/searchForModalByBoxUp")
	@ResponseBody
	public LayuiTableVoJA searchForModalByBoxUp(@ModelAttribute TsUserInfo cond){

		cond.addField("(A.UserId + '/' + A.UserName) AS nameLinked");

		cond.addField("C.UserName userLeaderName");//上级姓名
		cond.addField("O.DeptName AS deptName");
		cond.addField("R.Name AS roleName");
		cond.addField("PO.DeptName AS deptNameP");
		cond.addField("PR.Name AS roleNameP");
		cond.addLeftJoin("TS_OrganizationInfo O ON O.Orgid = A.DeptId ");
		cond.addLeftJoin("YS_Role R ON R.Id = A.RoleId");
		cond.addLeftJoin("TS_UserInfo C on C.UserId = A.UserLeader");
		cond.addLeftJoin("TS_OrganizationInfo PO ON PO.Orgid = C.DeptId");
		cond.addLeftJoin("YS_Role PR ON PR.Id = C.RoleId");

		cond.setOrderby("A.UserId asc");

		List<TbStaticConfig> tbStaticConfigList = new TbStaticConfig()
				.setKeyOne("TCC_FbaBoxUp")
				.setKeyTwo("boxUpUserIds")
				.queryList();
		if(tbStaticConfigList!=null && tbStaticConfigList.size()>0){
			StringBuilder res = new StringBuilder();
			for(TbStaticConfig item:tbStaticConfigList){
				if(res.length()>0){
					res.append(",");
				}
				res.append("'").append(item.getName()).append("'");
			}
			cond.where("A.UserId IN ("+res.toString()+")");
		}

		return commonApiService.searchLay(cond);
	}


	
}
